require 'oauth2'
require 'json'

class OauthController < ApplicationController

def index
	  begin
      params[:code] = session[:code] if !session[:code].nil?
      @consumer=OAuth2::Client.new('64670291c908100628d4e8254dbbb3c8488d79eb97d1045b915c5263caa6ff77', 'cef8bf16840c94bdfc6e0fe2ebc15f400c9588dbaa0fb72762010815f222b8a3', :site => "http://localhost:3000")
    	access_token = @consumer.auth_code.get_token(params[:code], :redirect_uri => 'http://localhost:3001/oauth/callback')
      session[:access_token] = access_token.token
      access_token = OAuth2::AccessToken.new(@consumer, session[:access_token])
      @photo = JSON.parse(access_token.get("/api/v1/me.json").body)
    rescue
      session[:uri] = "http://localhost:3001/oauth/index"
      redirect_to @consumer.auth_code.authorize_url(:redirect_uri => 'http://localhost:3001/oauth/callback')
    end
end

def callback
  session[:code] = params[:code]
  redirect_to session[:uri] + "?code="+params[:code]
end

end
